//
//  KeHuListViewController.m
//  JuBoCRM
//
//  Created by iMac on 2024/1/24.
//  Copyright © 2024 iningKe. All rights reserved.
//

#import "KeHuListViewController.h"
#import "KeHuListTableViewCell.h"
#import "KeHuLeiXingShaiXuanView.h"
#import "KeHuYeShaiXuanView.h"
#import "KeHuXiangQingViewController.h"
#import "XinJianKeHuViewController.h"
#import "ZiDingYiXuanChengYuanViewController.h"
#import "XinJianKeHuViewController.h"
#import "GongHaiKeHuXiangQingViewController.h"

#import "XinJianZongLanKeHuViewController.h"

@interface KeHuListViewController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>{
    KeHuLeiXingShaiXuanView *leiXingShaiXuanView;
    KeHuYeShaiXuanView *shaiXuanView;
    int page;
    NSMutableArray *dataSource;
    NSString *sceneId;
    NSDictionary *shaiXuanTiaoJianDic;
    
    NSArray *yuanGongArray;
    NSArray *buMengArray;
}
@property (weak, nonatomic) IBOutlet TPKeyboardAvoidingTableView *mainTableView;
@property (weak, nonatomic) IBOutlet UIButton *keHuShaiXuanButton;
@property (weak, nonatomic) IBOutlet UIButton *shaiXuanButton;
@property (weak, nonatomic) IBOutlet UIButton *keHuLeiXingButton;

@end

@implementation KeHuListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.customNavBar.hidden = YES;
    
    if (@available(iOS 11.0, *)) {
        self.mainTableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }
    
    
    [_mainTableView registerNib:[UINib nibWithNibName:@"KeHuListTableViewCell" bundle:nil] forCellReuseIdentifier:@"KeHuListTableViewCell"];
    
    leiXingShaiXuanView = [KeHuLeiXingShaiXuanView view];
    leiXingShaiXuanView.manageClickBlock = ^(NSString * _Nonnull result, NSString * _Nonnull resultName) {
        _keHuShaiXuanButton.selected = NO;
        leiXingShaiXuanView.hidden = YES;
        _keHuLeiXingButton.selected = NO;
        
        if([resultName isEqualToString:@"自定义"]){
            //自定义
            ZiDingYiXuanChengYuanViewController *shaiXuan = [[ZiDingYiXuanChengYuanViewController alloc] init];
            shaiXuan.manageResultBlock = ^(NSArray * _Nonnull yuanGongArray, NSArray * _Nonnull buMenArray) {
                yuanGongArray = yuanGongArray;
                buMengArray = buMenArray;
                
                [self downRefresh];
            };
            [self pushViewController:shaiXuan];
            return;
        }
        
        if(resultName.length > 0){
            [_keHuLeiXingButton setTitle:resultName forState:UIControlStateNormal];
            sceneId = result;
            [self downRefresh];
        }
       
    };
    
    
    [self.view addSubview:leiXingShaiXuanView];
    leiXingShaiXuanView.sd_layout
    .leftEqualToView(_mainTableView)
    .rightEqualToView(_mainTableView)
    .topEqualToView(_mainTableView)
    .bottomEqualToView(_mainTableView);
    leiXingShaiXuanView.hidden = YES;
    
    shaiXuanView = [KeHuYeShaiXuanView view];
    [self.view addSubview:shaiXuanView];
    shaiXuanView.sd_layout
    .leftEqualToView(_mainTableView)
    .rightEqualToView(_mainTableView)
    .topEqualToView(_mainTableView)
    .bottomEqualToView(_mainTableView);
    shaiXuanView.hidden = YES;
    shaiXuanView.toSelectYuanGongBuMenBlock = ^{
        ZiDingYiXuanChengYuanViewController *shaiXuan = [[ZiDingYiXuanChengYuanViewController alloc] init];
        shaiXuan.manageResultBlock = ^(NSArray * _Nonnull yuanGongArray, NSArray * _Nonnull buMenArray) {
            shaiXuanView.buMenChangYuan = [NSString stringWithFormat:@"已选择：%ld人，%ld部门",yuanGongArray.count,buMenArray.count];
            shaiXuanView.chengYuanArray = yuanGongArray;
            shaiXuanView.buMenArray = buMenArray;
        };
        [self pushViewController:shaiXuan];
    };
    
//    根据条件进行筛选
    shaiXuanView.manageResultBlock = ^(NSDictionary * _Nonnull resultDic) {
        shaiXuanView.hidden = YES;
        _shaiXuanButton.selected = NO;
        yuanGongArray = [NSArray array];
        buMengArray = [NSArray array];
        
        shaiXuanTiaoJianDic = resultDic;
        [self downRefresh];
    };
    
  
    MJRefreshNormalHeader *header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self downRefresh];
    }];

    _mainTableView.mj_header = header;
    
    MJRefreshAutoNormalFooter *footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self upRefresh];
    }];
    _mainTableView.mj_footer = footer;
        
        //查询搜索条件
    [self huoQuSouYouSouSuoTiaoJian];
        

  
    
}

//查询搜索条件
- (void)huoQuSouYouSouSuoTiaoJian{
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionary];
    [paraDic setValue:@"2" forKey:@"type"];
    [[ZZPRequest getWebUtil] postNetworkRequestURLString:@"/crmScene/queryScene" andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if(!error){
            NSMutableArray *array = [NSMutableArray arrayWithArray:[info objectForKey:@"data"]];
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
            [array addObject:dataDic];
            [dataDic setValue:@"自定义" forKey:@"name"];
            leiXingShaiXuanView.dataSource = array;
            
            if(leiXingShaiXuanView.dataSource.count > 0){
                sceneId = GetHandleString(leiXingShaiXuanView.dataSource.firstObject, @"sceneId");
                [_keHuLeiXingButton setTitle:GetHandleString(leiXingShaiXuanView.dataSource.firstObject, @"name") forState:UIControlStateNormal];
                page = 1;
                [self getInfoFromServer];
            }
                
        }
    }];
}


//上拉刷新
- (void)upRefresh {
    page++;
    [self getInfoFromServer];
}

//下拉刷新
- (void) downRefresh {
    page = 1;
    [self getInfoFromServer];
}

- (void)getInfoFromServer{
    
    NSMutableDictionary *paraDic = [NSMutableDictionary dictionaryWithDictionary:shaiXuanTiaoJianDic];
    
    
    if(buMengArray.count > 0 || yuanGongArray.count > 0){
        
        NSMutableArray *array = [NSMutableArray array];
        
        //    部门
        if(buMengArray.count > 0){
            NSMutableArray *temp = [NSMutableArray array];
            for (NSDictionary *tempD in buMengArray) {
                [temp addObject:GetHandleString(tempD, @"deptId")];
            }
            
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
            [dataDic setValue:@"structure" forKey:@"formType"];
            [dataDic setValue:@"ownerDeptId" forKey:@"name"];
            [dataDic setValue:@"3" forKey:@"type"];
            [dataDic setValue:temp forKey:@"values"];
            [array addObject:dataDic];
        }
        
        //    负责人
        if(yuanGongArray.count > 0){
            NSMutableArray *temp = [NSMutableArray array];
            for (NSDictionary *tempD in yuanGongArray) {
                [temp addObject:GetHandleString(tempD, @"userId")];
            }
            
            NSMutableDictionary *dataDic = [NSMutableDictionary dictionary];
            [dataDic setValue:@"user" forKey:@"formType"];
            [dataDic setValue:@"ownerUserId" forKey:@"name"];
            [dataDic setValue:@"3" forKey:@"type"];
            [dataDic setValue:temp forKey:@"values"];
            [array addObject:dataDic];
        }
        
        [paraDic setValue:array forKey:@"searchList"];
    }
    
    
    [paraDic setValue:[NSString stringWithFormat:@"%d",page] forKey:@"page"];
    [paraDic setValue:@10 forKey:@"limit"];
    [paraDic setValue:sceneId forKey:@"sceneId"];
    
    NSString *urlString = @"/crmCustomerAll/queryPageList";
    if ([_type intValue] == 0) {
        urlString = @"/crmCustomer/queryPageList";
        [paraDic setValue:@"2" forKey:@"type"];
    }else{
        [paraDic setValue:@"2" forKey:@"label"];
    }

    [[ZZPRequest getWebUtil] postJsonNetworkRequestURLString:urlString andParas:paraDic andShowHud:YES andTransferGottenData:^(id info, NSError *error) {
        if (!error) {
            NSLog(@"info:%@",info);
            NSArray *array = [[info objectForKey:@"data"] objectForKey:@"list"];
            if (page == 1) {
                if ([array count]> 9) {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    dataSource = [NSMutableArray arrayWithArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                    if(dataSource.count == 0){
                        _mainTableView.mj_footer.hidden = YES;
                    }else{
                        _mainTableView.mj_footer.hidden = NO;
                    }
                }
            }else {
                if ([array count]> 9) {
                    [dataSource addObjectsFromArray:array];
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshing];
                }else {
                    NSArray *tempArray = array;
                    if (tempArray.count > 0) {
                        [dataSource addObjectsFromArray:tempArray];
                    }
                    [_mainTableView.mj_header endRefreshing];
                    [_mainTableView.mj_footer endRefreshingWithNoMoreData];
                }
            }
            
            [_mainTableView reloadData];
            
            
        }else {
            [_mainTableView.mj_header endRefreshing];
            [_mainTableView.mj_footer endRefreshing];
        }
    }];
}
//用户类型筛选
- (IBAction)shaoXuanTiaoJian:(UIButton *)sender {
    
    _shaiXuanButton.selected = NO;
    shaiXuanView.hidden = YES;
    sender.selected = !sender.selected;
    
    leiXingShaiXuanView.hidden = !sender.selected;
    
}
//筛选
- (IBAction)shaiXuan:(UIButton *)sender {
    sender.selected = !sender.selected;
    _keHuShaiXuanButton.selected = NO;
    _keHuLeiXingButton.selected = NO;
    shaiXuanView.hidden = !sender.selected;
    leiXingShaiXuanView.hidden = YES;
}
//新建客户
- (IBAction)xinJian:(UIButton *)sender {
    if(_type.integerValue == 2){
        XinJianZongLanKeHuViewController *xinJian = [[XinJianZongLanKeHuViewController alloc] init];
        xinJian.manageClick = ^(NSInteger index) {
            [self downRefresh];
        };
        [self pushViewController:xinJian];
        return;
    }
    XinJianKeHuViewController *xinJian = [[XinJianKeHuViewController alloc] init];
    xinJian.manageClick = ^(NSInteger index) {
        [self downRefresh];
    };
    [self pushViewController:xinJian];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dataDic = dataSource[indexPath.row];
    if (_type.intValue == 2) {
        //客户全览
        return 240+[self getLabelHeightWithText:GetHandleString(dataDic, @"customerName") width:ScreenWidth-193]-52;
    }
    return 240+[self getLabelHeightWithText:GetHandleString(dataDic, @"customerName") width:ScreenWidth-193];
}
- (CGFloat)getLabelHeightWithText:(NSString *)text width:(CGFloat)width{ 
    CGRect rect = [text boundingRectWithSize:CGSizeMake(width, MAXFLOAT) options:NSStringDrawingUsesLineFragmentOrigin attributes:@{NSFontAttributeName:[UIFont systemFontOfSize:16 weight:UIFontWeightMedium]} context:nil];
    if(rect.size.height < 20){
        return 20;
    }
    return rect.size.height;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSDictionary *dataDic = dataSource[indexPath.row];
    KeHuListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"KeHuListTableViewCell"];
    cell.manageClickBlock = ^(NSInteger index) {
        if(index == 101){
            if([GetHandleString(dataDic, @"mobile") length] > 0){
                [ZZPUtils telephoneForAppWithNum:GetHandleString(dataDic, @"mobile")];
            }else{
                [ZZPUtils showWarning:@"暂无联系方式"];
            }
        }else{
            XinJianKeHuViewController *gongHai = [[XinJianKeHuViewController alloc] init];
            gongHai.customerId = GetHandleString(dataDic, @"customerId");
            [self.navigationController pushViewController:gongHai animated:YES];
        }
    };
    
    if (_type.intValue == 2) {
        //客户全览
        cell.jieDuanView.hidden = YES;
        cell.jieDuanViewHeight.constant = 0;
        cell.fuZeRenRemindLabel.text = @"来源";
        cell.genJinShiJianRedminLabel.text = @"负责人";
        cell.jinRuRemindLabel.text = @"跟进时间";
        cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
        cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
        cell.fuZeRenLabel.text = GetHandleString(dataDic, @"source");
        cell.genJinShiJianLabel.text = GetHandleString(dataDic, @"ownerUserName");
        cell.juLiGongHaiLabel.text = GetHandleString(dataDic, @"lastTime");
        cell.zhuangTaiLabel.text = GetHandleString(dataDic, @"level");
        
    }else{
        cell.jieDuanView.hidden = NO;
        cell.jieDuanViewHeight.constant = 52;
        cell.fuZeRenRemindLabel.text = @"负责人";
        cell.genJinShiJianRedminLabel.text = @"跟进时间";
        cell.jinRuRemindLabel.text = @"距进入公海";
        cell.nameLabel.text = GetHandleString(dataDic, @"customerName");
        cell.phoneLabel.text = GetHandleString(dataDic, @"mobile");
        cell.fuZeRenLabel.text = GetHandleString(dataDic, @"ownerUserName");
        cell.genJinShiJianLabel.text = GetHandleString(dataDic, @"lastTime");
        cell.juLiGongHaiLabel.text = [NSString stringWithFormat:@"%ld天",[GetHandleString(dataDic, @"poolDay") integerValue]];
        cell.zhuangTaiLabel.text = GetHandleString(dataDic, @"level");
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (_type.intValue == 2) {
        NSDictionary *dataDic = dataSource[indexPath.row];
        if ([GetHandleString(dataDic, @"ownerUserId") length] == 0) {
            GongHaiKeHuXiangQingViewController *xiangQing = [[GongHaiKeHuXiangQingViewController alloc] init];
            xiangQing.customerId = GetHandleString(dataDic, @"customerId");
            xiangQing.poolId = GetHandleString(dataDic, @"pool");
            xiangQing.manageClickResultBlock = ^(NSInteger result) {
                [self downRefresh];
            };
            [self pushViewController:xiangQing];
        }else{
            KeHuXiangQingViewController *xiangQing = [[KeHuXiangQingViewController alloc] init];
            NSDictionary *dataDic = dataSource[indexPath.row];
            xiangQing.customerId = GetHandleString(dataDic, @"customerId");
            xiangQing.juLiGongHaiNum = GetHandleString(dataDic, @"poolDay");
            xiangQing.shiBuShiZongLanKeHu = YES;
            xiangQing.manageClickResultBlock = ^(NSInteger result) {
                [self downRefresh];
            };
            [self pushViewController:xiangQing];
        }
        return;
    }
    
    KeHuXiangQingViewController *xiangQing = [[KeHuXiangQingViewController alloc] init];
    NSDictionary *dataDic = dataSource[indexPath.row];
    xiangQing.customerId = GetHandleString(dataDic, @"customerId");
    xiangQing.juLiGongHaiNum = GetHandleString(dataDic, @"poolDay");
    xiangQing.manageClickResultBlock = ^(NSInteger result) {
        [self downRefresh];
    };
    [self pushViewController:xiangQing];

}
//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
//    return -90;
//}

-(UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView{
    return [UIImage imageNamed:@"暂无搜索"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    
    NSMutableAttributedString *string = [[NSMutableAttributedString alloc] initWithString:@"暂无客户~"attributes: @{NSFontAttributeName: [UIFont systemFontOfSize:16],NSForegroundColorAttributeName: rgba(163, 168, 185, 1)}];
    return string;
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView{
    return YES;
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
